import math
from pydoc import text
import pyautogui
import time
import random
import os
import datetime
import json
import json
import os
import sys
import threading
import pyperclip
import win32gui
import win32process
import psutil
import subprocess
from PyQt5.QtWidgets import (QApplication, QMainWindow, QPushButton, 
                            QTextEdit, QVBoxLayout, QWidget)
from PyQt5.QtCore import Qt, QTimer, QObject, pyqtSignal
from MySQLHelper_walmart import MySQLHelper_walmart
import uuid
import random
from datetime import datetime
import traceback
import requests
import base64
import time
import pygetwindow as gw
import win32con

def get_disk_serial_simple():
    """获取第一个硬盘序列号（简化版）"""
    try:
        import wmi
        c = wmi.WMI()
        for disk in c.Win32_DiskDrive():
            if disk.SerialNumber:
                return disk.SerialNumber.strip()
        return None
    except Exception as e:
        print(f"Error getting disk serial: {e}")
        return None
# 添加新的类型注册方式
center_confidence=0.7
class MessageSender(QObject):
    textUpdateSignal = pyqtSignal(str)  # 简化信号定义

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.init_ui()
        # self.start_btn.click()
        self.show()
        self.sender = MessageSender()
        self.sender.textUpdateSignal.connect(self.text_memo.append)
        self.setGeometry(970, 340, 300, 1000)

        # print(ziniaoaccount)
        self.seqs=[]
        self.seqindex=0
        self.dbhelper=MySQLHelper_walmart()
        # self.ziniao_walmart_follow(5,'change')
        

    def init_ui(self):
        self.setWindowTitle('RPA跟卖')
        # self.start_btn = QPushButton('开始跟卖任务', self)
        # self.start_btn.clicked.connect(self.start_task)

        # self.change_btn = QPushButton('开始改价任务', self)
        # self.change_btn.clicked.connect(self.change_task)
        self.start_btn = QPushButton('开始跟卖,改价任务', self)
        self.start_btn.clicked.connect(self.start_task_thread)
         


        self.text_memo = QTextEdit(self)
        self.text_memo.setReadOnly(True)
        layout = QVBoxLayout()
        layout.addWidget(self.start_btn)
        layout.addWidget(self.text_memo)
        container = QWidget()
        container.setLayout(layout)
        self.setCentralWidget(container)
        
        # self.close_windows_by_processname('ziniao.exe')

    def start_task_thread(self):
        self.thread1=threading.Thread(target=self.start_task)
        self.thread1.daemon=True
        self.thread1.start()
    def start_task(self):
        """启动任务线程"""
        self.start_btn.setEnabled(False)

        current_dir = os.getcwd()
        json_file_path = os.path.join(current_dir, 'app', 'interface_walmart', 'rpa_login.json')
        sql='select * from app_zbirdaccount where is_active=1'
        ziniaoaccount=self.dbhelper.query(sql)
        for row in ziniaoaccount:
            print(row)
            self.ziniao_login(row['id'],row['loginname'],row['password'])
        
    
    def ziniao_login(self,zbird_account_id,ziniaoaccount,ziniaopassword):
        # self.check_country_origin_in_active_window()
 
        current_dir = os.getcwd()
        image_dirpath = os.path.join(current_dir, 'app', 'interface_walmart','png')
        # locaopen=pyautogui.locateOnScreen(image_path)
        # if locaopen:    
        #     print(locaopen)
        #     time.sleep(2.5)
        self.sender.textUpdateSignal.emit("开始执行任务...\n")
        self.sender.textUpdateSignal.emit("正在启动紫鸟客户端...\n")
        pyautogui.FAILSAFE = True
        pyautogui.PAUSE = 1
        orderindex=0
        addtionalheight=(orderindex -1)*88
        # 进行登录操作
        sql=f'select * from app_walmartaccount  where zbird_account_id={zbird_account_id}'
        walmartaccount=self.dbhelper.query(sql)
        if len(walmartaccount)==0:
            return
        subprocess.Popen(r"d:\Program Files\ziniao\ziniao.exe")
        time.sleep(0.5*random.random())
        self.set_window_position('ziniao.exe',1350,5,480,1000)
        while self.is_ziniaobrowser_window_exist('ziniao.exe')==False:
            time.sleep(0.5*random.random())
            self.sender.textUpdateSignal.emit('没有找到紫鸟窗口')

        # window_rect = list(self.get_window_info('ziniao.exe'))
        window_rect=[]
        window_rect.append(1350) 
        window_rect.append(5)
        window_rect.append(480)
        window_rect.append(1000)
        images=['triangel.png','logout.png','eplogin.png','epname.png','epinputpassword.png']
        # images=['logout.png','eplogin.png']
        time.sleep(random.random() * 2 + random.randint(2,3))
        pyautogui.doubleClick(random.randint(1400,1500),random.randint(25,30))
        for index,image in enumerate(images,start=1):
            image1=os.path.join(image_dirpath,image)
            if index==1:
                self.sender.textUpdateSignal.emit(image1)

            center=self.get_location_by_image(image1,window_rect)
            if center:
                self.sender.textUpdateSignal.emit(f"成功点击{image.replace('.png','')}")
                pyautogui.doubleClick(center[0],center[1])
                time.sleep(0.1*random.random())
            else:
                self.sender.textUpdateSignal.emit(f"没有找到，没有点击{image.replace('.png','')}")

        time.sleep(0.5*random.random())


        print('设置窗口位置')
        # pyautogui.click(1518,370)
        # 第三步张林余002
        time.sleep(0.5)
        # 输入登录账号
        x,y=window_rect[0]+random.randint(238,242), window_rect[1]+random.randint(475,480)
        print(x,y)
        pyautogui.click(x,y)
        # 登录账号输入位置，是顶部Y坐标增加477。
        # 密码输入位置，是顶部Y坐标增加542。
        # X坐标增加160张林余002
        pyautogui.press('backspace', presses=20)
        pyautogui.press('delete', presses=20)
        time.sleep(0.5)
        pyperclip.copy(ziniaoaccount)
        pyautogui.hotkey('ctrl', 'v') 
        self.sender.textUpdateSignal.emit(f'输入登录账号{ziniaoaccount}')

        # 第四步
        self.sender.textUpdateSignal.emit('输入登录密码')
        pyautogui.click(window_rect[0]+random.randint(238,242), window_rect[1]+random.randint(540,544))
        pyautogui.press('backspace', presses=20)
        pyautogui.press('delete', presses=20)

        time.sleep(0.5)
        pyautogui.write( ziniaopassword,interval=0.1)
        self.sender.textUpdateSignal.emit('输入密码后，按下回车')
        pyautogui.press('enter', presses=2)
        dirpath=os.path.join(os.getcwd(),'screenshot')
        os.makedirs(dirpath,exist_ok=True)
        # 直接登录了，直接登录了。进入紫鸟ziniaobrowser.exe界面
        time.sleep(0.5)
        print(f'当前沃尔玛账号数量:{len(walmartaccount)}')
        followtype='follow'
        # for row2 in walmartaccount:
        #     self.sender.textUpdateSignal.emit(f'开始{followtype},{row2["tag"]}')
        #     self.ziniao_walmart_follow(row2['id'],followtype)
        #     self.sender.textUpdateSignal.emit(f'结束{followtype},{row2["tag"]}')

        # self.sender.textUpdateSignal.emit(f'全部结束跟卖')
        followtype='change'
        action={'follow':'跟卖','change':'改价'}
        for row2 in walmartaccount:
            self.sender.textUpdateSignal.emit(f'开始{action[followtype]},{row2["tag"]}')
            self.ziniao_walmart_follow(row2['id'],followtype='follow')
            self.ziniao_walmart_follow(row2['id'],followtype='change')
            self.sender.textUpdateSignal.emit(f'结束{action[followtype]},{row2["tag"]}')    
            
        self.sender.textUpdateSignal.emit(f'全部结束{action[followtype]}')

    
    def is_ziniaobrowser_window_exist(self,exename='ziniaobrowser.exe'):
        """检查是否存在ziniaobrowser.exe进程的窗口"""
        window_found = False
        
        def callback(hwnd, _):
            nonlocal window_found
            try:
                _, pid = win32process.GetWindowThreadProcessId(hwnd)
                process = psutil.Process(pid)
                if exename in process.name().lower():
                    window_found = True
            except (psutil.NoSuchProcess, psutil.AccessDenied, PermissionError):
                return
            except Exception as e:
                print(f"窗口检查异常: {str(e)}")
                return
    
        win32gui.EnumWindows(callback, None)
        return window_found        
    def ziniao_walmart_follow(self,walmartaccountid,followtype='follow'):
        self.set_window_position('ziniao.exe',1350,5,480,1000)
        current_dir = os.getcwd()
        action={'follow':'跟卖','change':'改价'}
        image_dirpath = os.path.join(current_dir, 'app', 'interface_walmart','png')
        sqlwalmartaccount=f'select * from app_walmartaccount  where id={walmartaccountid}'
        row_walmart_account=self.dbhelper.query(sqlwalmartaccount)
        sellera=row_walmart_account[0]['loginname']
        tag=row_walmart_account[0]['tag']
        sql_a=f'select * from app_skus_new  where  current_cart_seller!="{sellera}" and newsku is null and price is not null and lastfollow_date is   null   and (upc is not null and   LENGTH(upc) > 6 ) and walmart_account_id={walmartaccountid}'
        sql2=f'select * from app_skus_new  where  current_cart_seller!="{sellera}" and newsku is null and price is not null and lastfollow_date is   null   and (upc is not null and   LENGTH(upc) > 6 ) and walmart_account_id={walmartaccountid}'
        if followtype=='change':
            sql2=f'select * from app_skus_new  where current_cart_seller!="{sellera}" and  newsku is not null and length(newsku)>5 and  abs(price+ifnull(deliveryfee,0)-price2-ifnull(olddeliveryfee,0)) >0.01 and (TIMESTAMPDIFF(MINUTE, lastchangeprice_date, NOW()) >= 720 or lastchangeprice_date is null) and walmart_account_id={walmartaccountid}'
            # sql2=f'select * from app_skus_new  where   newsku is not null and length(newsku)>5 and  walmart_account_id={walmartaccountid}'
        sql_b=f'select * from app_skus_new  where current_cart_seller!="{sellera}" and  newsku is not null and length(newsku)>5 and  abs(price+ifnull(deliveryfee,0)-price2-ifnull(olddeliveryfee,0)) >0.01 and (TIMESTAMPDIFF(MINUTE, lastchangeprice_date, NOW()) >= 720 or lastchangeprice_date is null) and walmart_account_id={walmartaccountid}'
        # print(sql2)
        data_a=self.dbhelper.query(sql_a)
        data_b=self.dbhelper.query(sql_b)
        if len(data_a)==0 and len(data_b  )==0:
            self.sender.textUpdateSignal.emit(f'账号不需要做跟卖，改价{sellera}')
            return
        data_app_skus=self.dbhelper.query(sql2)
        action_text=action[followtype]
        self.sender.textUpdateSignal.emit(f'{tag},{sellera}当前{action_text}sku数量:{len(data_app_skus)}')
        shutdowntimes=1000
        if len(data_app_skus)>=0:
            orderindex=row_walmart_account[0]['orderindex']
            # orderindex=2
            addtionalheight=(orderindex -1)*88
            # 打开一个沃尔玛新账号前，关闭窗口；
            if followtype=='follow':
                self.close_windows_by_processname('ziniaobrowser.exe')
                 # 第六步，等待出现新页面，在这里，选择账号，需要按照每个沃尔玛账号的顺序，进行点击
                self.human_like_move_and_click(1750, random.randint(230,240) + addtionalheight)
                time.sleep( random.random())
                self.set_window_position('ziniaobrowser.exe',1,1)
                time.sleep(random.random())
            # pyautogui.hotkey('ctrl', 'tab') #第一次点击紫鸟浏览器后，关闭多余的页签
            iy=1
            while followtype=='follow' and  self.is_ziniaobrowser_window_exist()==False:
                self.human_like_move_and_click(1750, random.randint(240 + (iy-1)*5,240+iy*5) + addtionalheight)
                iy+=1
                waittimeso=random.random()*2+3
                time.sleep(waittimeso)
                self.sender.textUpdateSignal.emit(f'等待紫鸟浏览器窗口出现!等待第{iy}次！,等待时间:{waittimeso}秒')

            self.set_window_position('ziniaobrowser.exe',1,0,1016,1006)
            if followtype=='follow':
                pyautogui.hotkey('ctrl', 'tab')     #这是新增加的代码
                
                center=self.get_location_by_image(os.path.join(image_dirpath,'noaccount.png'))
                if center:
                    self.human_like_move_and_click(center[0],center[1])
                    pyautogui.hotkey('ctrl', 'w') 
                tempclickimages=['tempnokown.png','noaccount.png']    
                for tempclickimage in tempclickimages:
                    center=self.get_location_by_image(os.path.join(image_dirpath,tempclickimage))
                    if center:
                        self.human_like_move_and_click(center[0],center[1])
                        time.sleep(random.random()*3)
            if followtype=='change':
                images=['goback.png']   
            if followtype=='follow':
                   images=['visitmany.png','openaccount.png','login.png','catalog.png','additems1.png']   
            self.set_window_position('ziniaobrowser.exe',1,0,1016,1006)
            image_path=os.path.join(image_dirpath,'visitmany.png')

            center=self.get_location_by_image(image_path)
            while not center:
                randwait=random.random()*0.5 
                time.sleep(randwait)
                self.sender.textUpdateSignal.emit(f'等待{randwait}秒')
                center=self.get_location_by_image(image_path)
                center_noaccount=self.get_location_by_image(os.path.join(image_dirpath,'noaccount.png'))
                if center_noaccount:
                    pyautogui.hotkey('ctrl', 'w') 
                    time.sleep(random.random()*0.5)
            for index,image in enumerate(images,start=1):
                image_path=os.path.join(image_dirpath,image)
                time.sleep(random.random()*0.5+ random.random()*1.8)
                if image=='login.png':
                    time.sleep(random.random()*0.3)
                    # self.human_like_move_and_click(random.randint(350,500),random.randint(200,250))
                    # time.sleep(random.random()*3)
                    self.human_like_move_and_click(random.randint(350,500),random.randint(200,250))
                center=self.get_location_by_image(image_path)
                if not center: 
                    if image=='login.png':
                        xtrytimes=0
                        xfound=0
                        while xtrytimes<10:
                            time.sleep(random.random())
                            center=self.get_location_by_image(image_path)
                            if center:
                                xfound=1
                            if center or xtrytimes>20:
                                break
                            xtrytimes+=1
                            self.sender.textUpdateSignal.emit(f'{xtrytimes},没有找到{image.replace(".png","")}，{xtrytimes}')

                            time.sleep(random.random()*0.5)

                        if xfound==0:
                            image_3='denglu.png'
                            xtrytimes=0
                            center=self.get_location_by_image(os.path.join(image_dirpath,image_3))
                            while not center:
                                xtrytimes+=1
                                time.sleep(random.random()*3)
                                center=self.get_location_by_image(image_path)
                                if center  :
                                    self.human_like_move_and_click(center[0],center[1])
                                if center or xtrytimes>20:
                                    self.human_like_move_and_click(center[0],center[1])
                                    break
                                self.sender.textUpdateSignal.emit(f'{xtrytimes},没有找到{image.replace(".png","")}，{xtrytimes}')
                    # 如果没有发现登录，但是发现了catalog，认为登录成功了。
                    
                    # image_path_c2=os.path.join(image_dirpath,'catalog.png')
                    # center=self.get_location_by_image(image_path_c2)
                    # if center:
                    #     time.sleep(random.random()*0.3)
                    #     continue
                    else:
                        maxtrytimes=200   
                        trytimes=0
                        while center is None or center ==False:  
                            time.sleep(0.1*random.random())
                            center=self.get_location_by_image(image_path)
                            if center:
                                print(f'成功找到{image}')
                                break
                            print(trytimes,f'没有找到{image}')
                            trytimes+=1
                            if trytimes>5:
                                time.sleep(random.random()*0.2 )
                                window_rect2=[]
                                window_rect2.append(350) 
                                window_rect2.append(5)
                                window_rect2.append(550)
                                window_rect2.append(40)
                                break
                        
                            
                        if index==5 or index==4:
                            # pyautogui.hotkey('f5' ) 
                            
                            # time.sleep(random.random()*2+ 0.2)
                            iyh=1
                            while True and iyh<10:
                                imagex1=os.path.join(image_dirpath,'catalog.png')
                                iyh+=1
                                centercata=self.get_location_by_image(imagex1)
                                if centercata:
                                    self.human_like_move_and_click(centercata[0],centercata[1]+random.randint(4+(iyh-1)*7,iyh*7))
                                    time.sleep(random.random()*0.5)
                                center=self.get_location_by_image(image_path)
                                if center:
                                    self.human_like_move_and_click(center[0],center[1])
                                    break
                        if index!=5:
                            center=self.get_location_by_image(image_path) 
                            if center:
                                self.human_like_move_and_click(center[0],center[1])    
                        break
                if center:
                        adheight=0
                        if index==4:
                            adheight=10
                        adwidth=0
                        if image=='goback.png':
                            adwidth=-20
                            pyautogui.click(center[0]+adwidth,center[1])
                        else:
                            self.human_like_move_and_click(center[0]+adwidth,center[1]+adheight)
                        if image=='catalog.png':
                            time.sleep(random.random()* 1.2)
                            center_add=self.get_location_by_image(os.path.join(image_dirpath,'addtiems1.png'))
                            iy3=1
                            while not  center_add and iy3<10:
                                self.human_like_move_and_click(center[0],center[1]+adheight + iy3*2)
                                time.sleep(random.random()*1.5)
                                center_add=self.get_location_by_image(os.path.join(image_dirpath,'addtiems1.png'))
                                iy3+=1
                            
                        self.sender.textUpdateSignal.emit(f'成功点击{image.replace(".png","")}按钮')
                        time.sleep(random.random()*0.5)
                else:
                    print(f'没有点击{image.replace(".png","")}')
                    self.sender.textUpdateSignal.emit(f'没有点击{image.replace(".png","")}')
            match(followtype):
                case 'follow':
                    self.ziniao_follow(row_walmart_account ,data_app_skus)  
                case 'change':
                    self.ziniao_change(row_walmart_account ,data_app_skus)   
   
    def ziniao_follow(self,row_walmart_account,data_app_skus):  
        followtimes=1000
        image_dirpath=os.path.join(os.getcwd(),'app','interface_walmart','png')
        addtionprice=-0.1
        username=row_walmart_account[0]['username']
        now = datetime.now()
        self.set_window_position('ziniaobrowser.exe',1,0,1016,1006)
        image_pathf=os.path.join(image_dirpath,'gtinupcfind.png')
        center=self.get_location_by_image(image_pathf)
        while not center:
            xrandtime=random.random()*0.5
            time.sleep(xrandtime)
            center=self.get_location_by_image(image_pathf)
            if center:
                break
            center2=self.get_location_by_image(os.path.join(image_dirpath,'additems1.png'))
            if center2:
                self.human_like_move_and_click(center2[0],center2[1])
                time.sleep(random.random()*0.8)
            self.sender.textUpdateSignal.emit(f'没有找到gtinupcfind，等候{xrandtime}秒')

        for index,row in enumerate(data_app_skus,start=1) :
            self.set_window_position('ziniaobrowser.exe',1,0,1016,1006)
            try:
                print(row['sku'])
                if index >followtimes:
                    break
                sku=row['sku']
                price=row['price'] if row['price'] else 0
                deliveryfee=row['deliveryfee'] if row['deliveryfee'] else 0
                if price==0 and deliveryfee==0:
                    self.sender.textUpdateSignal.emit(f'{sku}价格为0，跳过')
                    continue
                new_sku_code=self.get_sequence()
                print('sku,newsku,upc:',sku,new_sku_code,row['upc'])
                timestamp = str(int(time.time() ))
                tax_numeric_id=timestamp
                if index==1:
                    images=['gtinupcfind.png','additem2.png','newsku.png','sellingprice.png','measure.png','unitselect.png','tax.png','country.png','submit.png','itemsuccessfullysubmitted.png']
                else:
                    images=['rewriteupc.png','additem2.png','newsku.png','sellingprice.png','measure.png','unitselect.png','tax.png','country.png','submit.png','itemsuccessfullysubmitted.png']
                gooncontinueprocess=1
                for index_image,image in enumerate(images,start=1):
                    imagex=os.path.join(image_dirpath,image)
                    image_path=os.path.join(image_dirpath,image)
                    imagename=image.replace('.png','').lower()
                    print(imagename)
                    center=self.get_location_by_image(image_path)
                    if center:
                        print(center)
                        self.sender.textUpdateSignal.emit(f'成功点击{sku},{index}/{len(data_app_skus)},{index_image},{imagename}')
                    atrytimes=0
                    while not center:
                        atrytimes+=1
                        center=self.get_location_by_image(image_path)
                        if center:
                            break
                        if atrytimes>3:
                            break



                        
                    if not center:
                        match(imagename):
                            case 'gtinupcfind' | 'rewriteupc':
                         
                                if imagename=='rewriteupc': 
                                    image_path_3=os.path.join(image_dirpath,'gtinupcfind.png')
                                    center=self.get_location_by_image(image_path_3)
                                    if center:
                                        print('gtinupcfind',center)
                                else:
                                    image_path_3=os.path.join(image_dirpath,'rewriteupc.png')
                                    center=self.get_location_by_image(image_path_3)
                                    if center:
                                        print('rewriteupc',center)
                                self.sender.textUpdateSignal.emit(f'成功点击{sku},{index}/{len(data_app_skus)},{index_image},{image_path_3}')
                            case _:
                                center=self.get_location_by_image(image_path)
                                itrytimes=0
                                while not center:
                                    itrytimes+=1
                                    time.sleep(random.random()*0.5)
                                    center=self.get_location_by_image(image_path)
                                    self.sender.textUpdateSignal.emit(f'没有成功点击{sku}，{itrytimes},{index}/{len(data_app_skus)},{index_image},{imagename}')
                                    if itrytimes>1 and imagename not in ['newsku']:
                                        break
                        self.sender.textUpdateSignal.emit(f'没有点击{sku},{index}/{len(data_app_skus)},{index_image},{imagename}')
                        if index_image==1:
                            image_xxx=os.path.join(image_dirpath,'catalog.png')
                            center=self.get_location_by_image(image_xxx)
                            if center:
                                self.human_like_move_and_click(center[0],center[1])
                                time.sleep(random.random())
                                center=self.get_location_by_image(image_path)
                                if center:
                                    print(center)
                    addtionalitemheight=0
                    if gooncontinueprocess==0:
                        break
                    if center:
                        match(imagename):
                                
                            case 'newsku'| 'sellingprice' |   'country' | 'tax':  
                                addtionalitemheight=30
                                self.human_like_move_and_click(center[0]+random.randint(50,70),center[1]+ addtionalitemheight + int(30 * random.random() ))
                            case 'rewriteupc':
                                self.human_like_move_and_click(center[0] - random.randint(50,70),center[1]  )
                                time.sleep(0.1*random.random())
                       # 
                                pyautogui.press('backspace',15)
                                time.sleep(0.1*random.random())
                                pyautogui.press('delete')  
                                time.sleep(0.1*random.random())
                                pyautogui.press('backspace', presses=15)  # 按20次退格键
                                pyautogui.write(row['upc'], interval=0.1)
                                pyautogui.press('enter',presses=2)  

                                
                                time.sleep(2+random.random()*2)
                                image_edititem=os.path.join(image_dirpath,'edititem.png')
                                center2=self.get_location_by_image(image_edititem)
                                keyaction=''
                                upc2=''
                                if center2:
                                    upc2=row['upc']
                                    keyaction=f'产品已经跟卖过:upc->{upc2}'
                                    sql=f'update app_skus_new set lastfollow_date=now() where id={row["id"]}'
                                    self.dbhelper.execute(sql)
                                
                                image_edititem=os.path.join(image_dirpath,'cannnotfindtheitem.png')
                                center2=self.get_location_by_image(image_edititem)
                                if center2:
                                    keyaction=f'产品不存在:upc->{upc2}，无法跟卖'
                                if keyaction:
                                    self.sender.textUpdateSignal.emit(keyaction)
                                    sql=f'insert into sku_keywords_history (sku,opdate,username,keywords) values ("{sku}",now(),"{username}","{keyaction}")'
                                    print(sql)
                                    self.dbhelper.execute(sql)
                                    gooncontinueprocess=0
                                    break
                                # 检查是否跟卖过了，或者产品不存在，则关闭；并且写日志；

                            case _:
                                self.human_like_move_and_click(center[0]+random.randint(45,46),center[1]+ random.randint(1,2) )
                        time.sleep(0.5+ random.random()*0.8)
                        # 上述代码是第一步，找到位置，进行点击
                        match(imagename):
                            case 'gtinupcfind':
                                pyautogui.press('backspace', presses=20)  # 按20次退格键
                                pyautogui.write(row['upc'], interval=0.1)
                                pyautogui.press('enter',presses=2)  

                                time.sleep(random.random()*2)
                                # pyautogui.hotkey('ctrl', 'a') 
                                # 删除选中内容
                                
                                time.sleep(1+random.random()*0.6)
                                image_edititem=os.path.join(image_dirpath,'edititem.png')
                                center2=self.get_location_by_image(image_edititem)
                                keyaction=''
                                if center2:
                                    upc2=row['upc']
                                    keyaction=f'产品已经跟卖过:upc->{upc2}'
                                    sql=f'update app_skus_new set lastfollow_date=now() where id={row["id"]}'
                                    self.dbhelper.execute(sql)
                                
                                image_edititem=os.path.join(image_dirpath,'cannnotfindtheitem.png')
                                center2=self.get_location_by_image(image_edititem)
                                upc2=''
                                if center2:
                                    upc2=row['upc'] if row['upc'] else ''
                                    keyaction=f'产品不存在:upc->{upc2}，无法跟卖'
                                    

                                if keyaction:
                                    self.sender.textUpdateSignal.emit(keyaction)
                                    sql=f'insert into sku_keywords_history (sku,opdate,username,keywords) values ("{sku}",now(),"{username}","{keyaction}")'
                                    print(sql)
                                    self.dbhelper.execute(sql)
                                    gooncontinueprocess=0
                                    break
                                # 检查是否跟卖过了，或者产品不存在，则关闭；并且写日志；

                            case 'newsku':
                                pyautogui.press('backspace', presses=20)  # 按20次退格键
                                pyautogui.write(new_sku_code, interval=0.1)
                                pyautogui.press('enter',presses=2)     
                            case 'sellingprice':
                                deliveryfee=row['deliveryfee'] if row['deliveryfee'] else 0
                                pyautogui.write(str(float(price)+float(addtionprice)+float(deliveryfee)), interval=0.1)
                                pyautogui.press('enter',presses=2)     
                            case 'measure':
                                strweight=str(round(random.uniform(0.6, 1.0), 1))
                                pyautogui.write(strweight, interval=0.1)
                                pyautogui.press('enter',presses=2)   
                                
        
        
                            case 'unitselect':
                                self.human_like_move_and_click(center[0] - random.randint(-20,20), center[1] + random.randint(58,62))
                                time.sleep(random.random()*0.3)
                                    
                            case 'country':
                                #cx,cy=center[0] + random.randint(350,410), center[1] - random.randint(400,450)
                                cx,cy=center[0] + random.randint(390,410), center[1] - random.randint(420,470)
                                self.human_like_move_and_click(cx,cy)
                                self.human_like_move_and_click(cx,cy)
                                intcontinue=1
                                for ix in range(40):
                                    if intcontinue==0:
                                        continue
                                    pyautogui.scroll(-120)
                                    time.sleep(0.2*random.random())
                                    if ix >6:
                                        centerc=self.get_location_by_image(os.path.join(image_dirpath,'china.png'))
                                        if centerc:
                                            self.human_like_move_and_click(centerc[0] , centerc[1]  ) 
                                            intcontinue=0
                            case 'tax':
                                pyautogui.write(tax_numeric_id, interval=0.1)
                                time.sleep(random.random()*0.3)
                                # pyautogui.press('enter',presses=2) 
                            case "submit":
                                for ix in range(6):
                                    pyautogui.scroll(-240)
                                    time.sleep(0.2*random.random()) 
                                time.sleep(random.random()*0.8)

                            case 'itemsuccessfullysubmitted':
                                pyautogui.hotkey('ctrl', 'w') 
                                sql=f'insert into sku_keywords_history (sku,opdate,fromprice,toprice,username) values ("{sku}",now(),0,{price},"{username}")'
                                print(sql)
                                self.dbhelper.execute(sql)
                                sql=f'update app_skus_new set newsku="{new_sku_code}",newprice={float(price)+float(addtionprice)},lastfollow_date=now() where id={row["id"]}'
                                print(sql)
                                self.dbhelper.execute(sql)
                    time.sleep(0.2*random.random())
            except Exception as e:
                print(f'跟卖失败{sku}-> ->{price}')
                traceback.print_exc()   
                self.sender.textUpdateSignal.emit(f'跟卖失败{traceback.format_exc()}')
        print('处理完毕')    
    def ziniao_change(self,row_walmart_account,data_app_skus):  
        image_dirpath=os.path.join(os.getcwd(),'app','interface_walmart','changepng')
        addtionprice=-0.1
        username=row_walmart_account[0]['username']
        now = datetime.now()
        self.set_window_position('ziniaobrowser.exe',1,0,1280,1015)
        time.sleep(random.random()*random.randint(10,13))
        for index,row in enumerate(data_app_skus,start=1) :
            try:
                self.set_window_position('ziniaobrowser.exe',1,0,1280,1015)
                print(row['newsku'])
                sku=row['newsku']
                oldprice=row['price2']
                newprice=row['price']
                new_sku_code=row['newsku']
                print('new_sku_code,newprice,oldprice:',new_sku_code,newprice,oldprice)
                if index==1:
                    images=['searchbysku.png','price_ca_1.png','price_toclick.png']
                else:
                    images=['searchbysku_2.png','price_ca_1.png','price_toclick.png']
                canfollow=1
                for index_image,image in enumerate(images,start=1):
                    imagex=os.path.join(image_dirpath,image)

                    image_path=os.path.join(image_dirpath,image)
                    imagename=image.replace('.png','').lower()
                    print(imagename)
                    if canfollow==0:
                        continue
                    center=self.get_location_by_image(image_path)
                    if center:
                        print(center)
                        self.sender.textUpdateSignal.emit(f'成功点击{sku},{index}/{len(data_app_skus)},{index_image},{imagename}')
                    else:
                        if imagename=='searchbysku_2':
                            image_3='searchbysku.png'
                            image_path_3=os.path.join(image_dirpath,image_3)
                            center=self.get_location_by_image(image_path_3)
                            if center:
                                print(center)
                                self.sender.textUpdateSignal.emit(f'成功点击{sku},{index}/{len(data_app_skus)},{index_image},{image_path_3}')
                        if imagename=='searchbysku':
                            image_3='searchbysku_2.png'
                            image_path_3=os.path.join(image_dirpath,image_3)
                            center=self.get_location_by_image(image_path_3)
                            if center:
                                print(center)
                                self.sender.textUpdateSignal.emit(f'成功点击{sku},{index}/{len(data_app_skus)},{index_image},{image_path_3}')
                        self.sender.textUpdateSignal.emit(f'没有点击{sku},{index}/{len(data_app_skus)},{index_image},{imagename}')
                    addtionalitemheight=0
                    if center:      
                        match(imagename):
                            case 'price_ca_1':  
                                addtionalitemheight=62  
                                self.human_like_move_and_click(center[0]+random.randint(1,3),center[1]+ random.randint(58,67) )
                                time.sleep(0.5+ random.random())
                            case 'searchbysku'| 'searchbysku_2': 
                                print(f'搜索sku:{row["newsku"]}')
                                self.human_like_move_and_click(center[0]- random.randint(51,52),center[1] )   
                                pyautogui.press('backspace',random.randint(15,20))
                                time.sleep(0.1*random.random())
                                pyautogui.press('delete',random.randint(15,20))  
                                time.sleep(0.1*random.random())
                                pyautogui.write(str(row['newsku']), interval=0.1)
                                pyautogui.press('enter',presses=random.randint(1,2))  
                                                                # 改进后的回车操作
                                for _ in range(2):  # 固定执行2次确保触发
                                    pyautogui.keyDown('enter')
                                    time.sleep(random.uniform(0.05, 0.1))  # 添加随机延迟
                                    pyautogui.keyUp('enter')
                                    time.sleep(random.uniform(0.1, 0.3))   # 按键间添加随机间隔
                                time.sleep(random.uniform(0.2, 0.5))    
                                # pyautogui.write(str(row['upc']), interval=0.1)
                                newsku_3=str(row['newsku'])
                                time.sleep(1+ random.random()*0.8)
                                foundover=0
                                pic_path=os.path.join(image_dirpath,f'screenshot_{newsku_3}.png')
                                ytrytimes=0
                                while True:
                                    image_edititem=os.path.join(image_dirpath,'noskufoundtochangeprice.png')
                                    center2=self.get_location_by_image(image_edititem)
                                    
                                    ytrytimes+=1
                                    if ytrytimes>3:
                                        break
                                    pyautogui.screenshot(os.path.join(image_dirpath,f'screenshot_{newsku_3}.png'))

                                    if center2:
                                        keyaction=f'产品不存在:sku->{sku}，无法跟价改价'
                                        self.sender.textUpdateSignal.emit(keyaction)
                                        sql=f'insert into sku_keywords_history (sku,opdate,username,keywords) values ("{sku}",now(),"{username}","{keyaction}")'
                                        print(sql)
                                        self.dbhelper.execute(sql)
                                        foundover=1
                                        canfollow=0
                                        break
                                    time.sleep(1+ random.random()*0.8)
                            
                                    
                            case 'price_toclick':
                                self.human_like_move_and_click(center[0] + random.randint(50,70),center[1]  )
                                pyautogui.press('backspace',random.randint(7,8))
                                time.sleep(0.1*random.random())
                                pyautogui.press('delete',random.randint(7,8))  
                                time.sleep(0.1*random.random())
                                print('最新价格',row['price'])
                                deliveryfee=row['deliveryfee'] if row['deliveryfee'] else 0
                                realprice=float(row['price'])  if row['price'] else 0
                                pyautogui.write(str(round(realprice-0.1 + deliveryfee,2) ), interval=0.1) 
                                pyautogui.press('enter',presses=2) 
                                time.sleep(1+ random.random()*2)
                                for ix1 in range(2):
                                    pyautogui.press('tab',presses=1) 
                                    time.sleep(0.1*random.random())
                                pyautogui.press('enter',presses=2) 
                                self.sender.textUpdateSignal.emit(f'{sku}->{row["price"]}->{row["price2"]}')
                                sql=f'insert into sku_keywords_history (sku,opdate,username,keywords) values ("{sku}",now(),"{username}","修改价格从{oldprice}到{newprice}")'
                                print(sql)
                                self.dbhelper.execute(sql)
                                sql=f'update app_skus_new set price2={newprice},lastchangeprice_date=now() where id={row["id"]}'
                                print(sql)
                                self.dbhelper.execute(sql)
                            case 'updateprice':
                                self.human_like_move_and_click(center[0]  ,center[1]  )
                                
                        time.sleep(0.2*random.random())
            except Exception as e:
                self.sender.textUpdateSignal.emit(f'跟价改价失败{traceback.format_exc()}')
                traceback.print_exc()   
        print('处理完毕')    
    def get_location_by_image(self,image_path,window_rect=(1, 0, 1300, 1200)):
        try:
            
            if os.path.exists(image_path):
                # 格式：(left, top, width, height)
                locaopen = pyautogui.locateOnScreen(
                    image_path,
                    confidence=center_confidence,
                    minSearchTime=3,
                    region=window_rect  #
                )
                if locaopen:
                    center = pyautogui.center(locaopen)
                    # 点击图像中心
                    return center
                else:
                    return None
            else:
                return None
        except Exception as e:
            print(f'出现异常{image_path}->{e}')
            # traceback.print_exc()
            return None
    

    def human_like_move_and_click(self, dest_x, dest_y, duration=0.3, click=True):
        try:
            # 简化移动路径计算
            start_x, start_y = pyautogui.position()
            distance = math.hypot(dest_x - start_x, dest_y - start_y)
            
            # 减少移动步数（从5步减少到3步）
            steps = max(int(distance / 250), 3)  # 增大单步距离
            step_time = duration / steps * 0.5  # 减少单步时间
            
            # 使用直线加速移动（取消路径扰动）
            for i in range(steps):
                t = (i + 1) / steps
                current_x = start_x + (dest_x - start_x) * t
                current_y = start_y + (dest_y - start_y) * t
                pyautogui.moveTo(current_x, current_y, duration=step_time)
            
            # 快速点击优化
            if click:
                # 移除点击前犹豫
                pyautogui.mouseDown()
                time.sleep(0.02)  # 减少按压时间
                pyautogui.mouseUp()
                
                # 缩短点击后停留
                time.sleep(0.05)  # 从0.3秒减少到0.05秒

        except Exception as e:
            print(f"快速移动失败: {str(e)}")
    def set_window_position(self, exename, destx, desty, width=1016, height=1006):
        try:
            def callback(hwnd, _):
                try:
                    _, pid = win32process.GetWindowThreadProcessId(hwnd)
                    process = psutil.Process(pid)
                    if exename.lower() in process.name().lower():
                        # 恢复最小化窗口
                        if win32gui.IsIconic(hwnd):
                            win32gui.ShowWindow(hwnd, win32con.SW_RESTORE)
                        # # 激活窗口到前台
                        win32gui.SetForegroundWindow(hwnd)
                        win32gui.MoveWindow(hwnd, destx, desty, width, height, True)
                except (psutil.NoSuchProcess, psutil.AccessDenied, PermissionError):
                    return
                except Exception as e:
                    print(f"进程处理异常: {str(e)}")
                    return
            # 枚举所有窗口
            win32gui.EnumWindows(callback, None)
            return True
        except Exception as e:
            print(f"窗口移动失败: {e}")
            return False
    def close_windows_by_processname(self,processname):
        """关闭所有ziniaobrowser.exe进程的窗口"""
        try:
            def callback(hwnd, _):
                try:
                    # 获取窗口的进程ID
                    _, pid = win32process.GetWindowThreadProcessId(hwnd)
                    # 获取进程对象
                    process = psutil.Process(pid)
                    # 检查进程名称是否包含目标字符串
                    if  processname.lower() in process.name().lower():
                        # 发送关闭消息
                        win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
                except (psutil.NoSuchProcess, psutil.AccessDenied, PermissionError):
                    return
                except Exception as e:
                    print(f"窗口关闭异常: {str(e)}")
                    return
                    
            # 枚举所有窗口
            win32gui.EnumWindows(callback, None)
            return True
        except Exception as e:
            print(f"窗口关闭失败: {e}")
            return False
    def closeEvent(self, event):
        """窗口关闭时停止线程"""
        
        event.accept()
    def get_sequence(self):
        newseq=''       
        
        if self.seqindex>=100 or not self.seqs:
            self.seqindex=0
            self.seqs=self.dbhelper.get_next_sequence()

        if self.seqs and self.seqindex<100:
            newseq= self.seqs[self.seqindex]

        self.seqindex+=1 
        return newseq   
    def get_window_info(self, exename):
        """获取指定进程窗口的位置和尺寸信息"""
        def callback(hwnd, results):
            try:
                _, pid = win32process.GetWindowThreadProcessId(hwnd)
                process = psutil.Process(pid)
                if exename.lower() in process.name().lower():
                    rect = win32gui.GetWindowRect(hwnd)
                    left, top, right, bottom = rect
                    results.append((
                        left, 
                        top, 
                        right - left,  # width
                        bottom - top   # height
                    ))
            except (psutil.NoSuchProcess, psutil.AccessDenied, PermissionError):
                return
            except Exception as e:
                print(f"窗口信息获取异常: {str(e)}")
                return

        results = []
        win32gui.EnumWindows(callback, results)
        return results[0] if results else None  
    def process_text_input(self, tax_image_path, input_text,addtionalwidth=14, addtionalheight=56):
        # 步骤1：定位tax标签
        tax_center = self.get_location_by_image(tax_image_path)
        if not tax_center:
            print("未找到tax标签")
            return False

        # 步骤2：计算文本框坐标（tax标签下方56像素）
        textfield_x = tax_center[0] + random.randint(10, addtionalwidth*2)  # 横向随机偏移
        textfield_y = tax_center[1] + 56 + random.randint(30, addtionalheight)  # 纵向偏移+随机
        
        # 步骤3：模拟人工点击输入
        try:
            # 移动并点击文本框
            self.human_like_move_and_click(textfield_x, textfield_y)
            
            # 清空现有内容
            pyautogui.hotkey('ctrl', 'a')
            time.sleep(0.2)
            pyautogui.press('backspace')
            
            # 输入内容（带随机间隔）
            for char in input_text:
                pyautogui.write(char, interval=random.uniform(0.05, 0.15))
                if random.random() < 0.1:  # 10%概率输入错误并修正
                    pyautogui.press('backspace')
                    pyautogui.write(char)
            
            # 验证输入
            pyautogui.hotkey('ctrl', 'a')
            pyautogui.hotkey('ctrl', 'c')
            time.sleep(0.3)
            clipboard_text = pyperclip.paste()
            
            if clipboard_text == input_text:
                print("输入验证成功")
                return True
            else:
                print("输入验证失败，尝试重新输入")
                return self.process_tax_input(tax_image_path, input_text)  # 递归重试
        except Exception as e:
            print(f"输入过程中发生错误: {str(e)}")
            return False

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    # window.get_sequence()
    sys.exit(app.exec_())

